<?php

	/**
	 * mysql result set -> array
	 *
	 * @param object $result mysql result set
	 * @param int $autoConvert whether convert to 1 dimention
	 * @return array
	 */
	function dbresult2array(&$result, $autoConvert=1)
	{
		$arrTrans = array();
		for ($i=0; $i < $result->num_rows; $i++)
		{
			$row = $result->fetch_assoc();
			foreach ($row as $key=>$value)
			{
				$arrTrans[$i][$key] = $value ;
			}
		}
		return ($autoConvert==1 && $result->num_rows==1) ? $arrTrans[0] : $arrTrans;
		//如果结果行数为1，返回一维数组
		//其他情况，返回一个二位数组
	}

	function dbresult2arrayII(&$result)
	{
		$arrTrans = array();
		for ($i=0; $i < $result->num_rows; $i++)
		{
			$row = $result->fetch_assoc();
			foreach ($row as $key=>$value)
			{
				$arrTrans[$i][$key] = $value ;
			}
		}
		return $arrTrans;
		//无论结果是否单行，都返回一个二位数组
	}
	
	/**
	 * 二维数组按行整理成字符串
	 *
	 * @param array $d2array
	 * @param string $delimiter 每行的字符串连接符
	 * @param string $linebreaker 换行符
	 * @return string
	 */
	function d2array2str($d2array, $delimiter=',', $linebreaker="\n")
	{
		$strReturn = '';
		foreach ($d2array as $value)
		{
			$strReturn .= implode($delimiter, $value).$linebreaker;
		}
		return $strReturn;
	}

	/**
	 * 正则表达式检查
	 *
	 * @param string $item 检查的项目
	 * @param mixed $value 检查的值
	 * @param boolean $filterlib 是否使用filter ext
	 * @param mixed $option filter ext的option
	 * @return boolean
	 */
	function filterCheck($item, $value, $filterlib=0, $option=NULL)
	{
		if ($filterlib==0 && $GLOBALS['cfg']['regexp'][$item])
		{
			return preg_match($GLOBALS['cfg']['regexp'][$item], $value);
		}
		else  // 调用PHP内置的FILTER库，进行Validate
		{
			$arrFilter = array(
				'int'     =>  FILTER_VALIDATE_INT,
				'float'   =>  FILTER_VALIDATE_FLOAT,
				'boolean' =>  FILTER_VALIDATE_BOOLEAN,
				'url'     =>  FILTER_VALIDATE_URL,
				'email'   =>  FILTER_VALIDATE_EMAIL,
				'regexp'  =>  FILTER_VALIDATE_REGEXP,
				'ip'      =>  FILTER_VALIDATE_IP
			);
			return (filter_var($value, $arrFilter[$item], $option)==$value);
			//filter ext的函数如果过滤正确，返回的是原始值
			//如果原始值是0或者什么的，有可能返回值就不正确了
		}
	}

	/**
	 * mysql escape
	 *
	 * @param string $strInput
	 * @return string
	 */
	function mysqlEscape($strInput)
	{
		return str_replace( 
			array('\\'  , '\''  , '"' , '%' , '_'  ), 
			array('\\\\', '\\\'', '\"', '\%', '\_' ), 
			$strInput 
		);
	}
	
	
	function xss_check_url( $url )
	{
		$url = trim( urldecode( $url ) );
		
		if ( ! preg_match( "#^https?://(?:[^<>*\"]+|[a-z0-9/\._\- !]+)$#iU", $url ) )
		{
			return FALSE;
		}

		return TRUE;
	}

	
	/*-------------------------------------------------------------------------*/
	// Get OS
	// Return: unknown, windows, mac
	/*-------------------------------------------------------------------------*/
	
	/**
	* Fetches the user's operating system
	*
	* @return	string
	*/
	
	function fetch_os()
	{
		$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
		
		if ( strstr( $useragent, 'mac' ) )
		{
			return 'mac';
		}
		
		if ( preg_match( '#wi(n|n32|ndows)#', $useragent ) )
		{
			return 'windows';
		}
		
		return 'unknown';
	}
	
	/*-------------------------------------------------------------------------*/
	// Get browser
	// Return: unknown, opera, IE, mozilla, konqueror, safari
	/*-------------------------------------------------------------------------*/
	
	/**
	* Fetches the user's browser from their user-agent
	*
	* @return	array [ browser, version ]
	*/
	
	function fetch_browser()
	{
		$version   = 0;
		$browser   = "unknown";
		$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
		
		//-----------------------------------------
		// Opera...
		//-----------------------------------------
		
		if ( strstr( $useragent, 'opera' ) )
		{
			preg_match( "#opera[ /]([0-9\.]{1,10})#", $useragent, $ver );
			return array( 'browser' => 'opera', 'version' => $ver[1] );
		}
		
		//-----------------------------------------
		// IE...
		//-----------------------------------------
		
		if ( strstr( $useragent, 'msie' ) )
		{
			preg_match( "#msie[ /]([0-9\.]{1,10})#", $useragent, $ver );
			return array( 'browser' => 'ie', 'version' => $ver[1] );
		}
		
		//-----------------------------------------
		// Safari...
		//-----------------------------------------
		
		if ( strstr( $useragent, 'safari' ) )
		{
			preg_match( "#safari/([0-9.]{1,10})#", $useragent, $ver );
			return array( 'browser' => 'safari', 'version' => $ver[1] );
		}
		
		//-----------------------------------------
		// Mozilla browsers...
		//-----------------------------------------
		
		if ( strstr( $useragent, 'gecko' ) )
		{ 
			preg_match( "#gecko/(\d+)#", $useragent, $ver );
			return array( 'browser' => 'gecko', 'version' => $ver[1] );
		}
		
		//-----------------------------------------
		// Older Mozilla browsers...
		//-----------------------------------------
		
		if ( strstr( $useragent, 'mozilla' ) )
		{
			preg_match( "#^mozilla/[5-9]\.[0-9.]{1,10}.+rv:([0-9a-z.+]{1,10})#", $useragent, $ver );
			return array( 'browser' => 'mozilla', 'version' => $ver[1] );
		}
		
		//-----------------------------------------
		// Konqueror...
		//-----------------------------------------
		
		if ( strstr( $useragent, 'konqueror' ) )
		{
			preg_match( "#konqueror/([0-9.]{1,10})#", $useragent, $ver );
			return array( 'browser' => 'konqueror', 'version' => $ver[1] );
		}

		//-----------------------------------------
		// Still here?
		//-----------------------------------------
		return array( 'browser' => $browser, 'version' => $version );
	}

	function checkBrowser($browser)
	{
		$arrBrowser = fetch_browser();
		return $browser==$arrBrowser['browser'];
	}
	
	/*****UTF-8 substr*****/
	function mySubstr($str, $from, $len)
	{
	    return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
	                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
	                       '$1',$str);
	}
	

	
	/*****anti-SQL inj*****/
	function secChk($info)
	{
		if(!$info) return true;
		foreach($info as $value)
		{
			foreach($GLOBALS['cfg']['sec']['forbidden'] as $kw)
				if (stristr($value, $kw)) return false;
		}
		return true;
	}



	/*****resize pic*****/
	function createBreviaryImage($srcImage, $toFile, $maxWidth=90, $maxHeight=90, $imgQuality=100){
	list($width, $height, $type, $attr) = getimagesize($srcImage);
	switch ($type) {
	case 1: $img = imagecreatefromgif($srcImage); break;
	case 2: $img = imagecreatefromjpeg($srcImage); break;
	case 3: $img = imagecreatefrompng($srcImage); break;
	}
	$scale = min($maxWidth/$width, $maxHeight/$height);
	if($scale < 1) {
	$newWidth = floor($scale*$width);
	$newHeight = floor($scale*$height);
	$newImg = imageCreatetruecolor($newWidth, $newHeight);

	if ($type == 3)
	{
		imagealphablending($newImg, false);
		imagesavealpha($newImg, true);
	}

	if ($type == 3 || $type == 1)
	{
		$b = ImageColorAllocate($newImg, 0xcc, 0xcc, 0xcc);
		imagefill($newImg, 0, 0, $b);
		$t = imagecolortransparent ($newImg, $b);
	}


	ImageCopyResampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

	switch($type) {
	case 1: if(imagegif($newImg, "$toFile", $imgQuality))
	return "$toFile"; break;
	case 2: if(imagejpeg($newImg, "$toFile", $imgQuality))
	return "$toFile"; break;
	case 3: if(ImagePng($newImg, "$toFile"))
	return "$toFile"; break;
	default: if(imagejpeg($newImg, "$toFile", $imgQuality))
	return "$toFile"; break;
	}
	imageDestroy($newImg);
	}
	imageDestroy($img);
	return false;
	}
?>
